package net.easyjava.tools.json.filter;

import net.easyjava.tools.json.convert.JsonDateValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import java.util.Date;

/**
 * Created by shhao.
 * Date: 14-6-11
 * Time:下午3:19
 */
public class FilterProperty {

    static JsonDateValueProcessor jsonDateValueProcessor = new JsonDateValueProcessor();

    //JSONArray
    public JSONArray configJsonArray(Object obj, String excludeProperties) {
        JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        String[] fields = null;
        if (-1 != excludeProperties.indexOf(",")) {
            fields = excludeProperties.split(",");
        } else {
            fields = new String[]{excludeProperties};
        }
        if (null != fields)
            config.setJsonPropertyFilter(new IgnoreFieldProcessorImpl(fields));
        config.registerJsonValueProcessor(Date.class, jsonDateValueProcessor);
        return JSONArray.fromObject(obj, config);
    }


    // JsonObject
    public JSONObject configJsonObject(Object obj, String excludeProperties)  {
        JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        String[] fields = null;
        if (-1 != excludeProperties.indexOf(",")) {
            fields = excludeProperties.split(",");
        } else {
            fields = new String[]{excludeProperties};
        }
        if (null != fields)
            config.setJsonPropertyFilter(new IgnoreFieldProcessorImpl(fields));
        config.registerJsonValueProcessor(Date.class, jsonDateValueProcessor);
        return JSONObject.fromObject(obj, config);
    }

}
